<?php

namespace app\models\product;

use app\models\Brand;
use app\models\constant\Status;
use app\models\Images;
use app\models\NewLevel;
use app\models\order\Order;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserLevel;
use Yii;

/**
 * This is the model class for table "product".
 *
 * @property int $id
 * @property int $category_id 分类
 * @property string $title 标题
 * @property string $title_sub 子标题
 * @property float $price 价格
 * @property float $price_old 原价
 * @property float $price_cost 成本
 * @property float|null $freight 运费(偏远地区), 后期改成运费模板
 * @property int $stock 库存
 * @property int $status 1开 0关, -99删除
 * @property int $sort 排序
 * @property string|null $content 商品内容
 * @property string $create_time
 * @property string $update_time
 * @property int $area_id 哪个区
 * @property int $brand_id 品牌
 * @property int $main_image 主图
 * @property int $is_recommend 是否为推荐商品
 * @property int $score_cost_id 积分运营费用
 * @property string $supplier 供应商
 */
class Product extends \yii\db\ActiveRecord
{
    use Status;

    public static $areaMap = [
        'GROUP' => 5,

        'SCORE' => 2,

        // 报单, 复购, 秒杀, 商品区
        'REPORT' => 1,
        'REPEAT' => 6,
        'KILL' => 4,
        'GENERAL' => 3,

        // 预售 盲盒 0元区（类似积分区）
        'PRESALE' => 8,
        'BIND_Box' => 9,
        'ZERO' => 10,

        // 福利区
        'F' => 11,
    ];

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'product';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            // [['category_id', 'stock', 'status', 'sort', 'brand_id', 'main_image'], 'integer'],
            [['category_id', 'stock', 'status', 'sort', 'brand_id', 'main_image'], 'safe'],
            [['price', 'price_old', 'price_cost', 'freight'], 'number'],
            [['content'], 'string'],
            [['create_time', 'update_time'], 'safe'],
            [['title', 'title_sub'], 'string', 'max' => 255],

            [['is_recommend', 'score_cost_id'], 'safe'],

            [['supplier', 'f', 'limit_count', 'box'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'category_id' => 'Category ID',
            'title' => 'Title',
            'title_sub' => 'Title Sub',
            'price' => 'Price',
            'price_old' => 'Price Old',
            'price_cost' => 'Price Cost',
            'freight' => 'Freight',
            'stock' => 'Stock',
            'status' => 'Status',
            'sort' => 'Sort',
            'content' => 'Content',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'brand_id' => 'Brand ID',
            'main_image' => 'Main Image',
        ];
    }

    // 检查是否为复购(返佣时, 有购买的订单存在)
    public static function checkRepeat(User $user, $order_id = 0)
    {
        // 1 user -> repeat = 1
        // 2 存在订单

        if ($user->repeat == 1) {
            $count = Order::find()
                ->where(['user_id' => $user->id])
                ->andWhere(['!=', 'status', 0])
                ->andWhere(['!=', 'status', -99])
                ->andWhere(['!=', 'status', 5]);
            if ($order_id) {
                $count->andWhere(['!=', 'id', $order_id]);
            }
            if ($count->count() > 0) {
                return true;
            }
        }

        return false;
    }

    // 复购价格
    public static function getPriceByLevel($product_id, $user_id, $price)
    {

        // return $price;

        // 复购85折
        // $set = SetUserUp::getLastOne();
        // return $price * $set->repeat / 100;

        $user = User::findOne(['id' => $user_id]);
        $level = $user->level;

        // 这里修改成只能"复购区"才有复购价了
        // 如果是复购
        // if (self::checkRepeat($user)) {
        if (ProductArea::checkRepeat($product_id)) {

            $set = SetUserUp::getLastOne();

            if ($level == UserLevel::$keys['vip1']) {
                return $price / 10 * $set->re_vip1;
            }
            if ($level == UserLevel::$keys['vip2']) {
                return $price / 10 * $set->re_vip2;
            }
            if ($level == UserLevel::$keys['vip3']) {
                return $price / 10 * $set->re_vip3;
            }
            if ($level == UserLevel::$keys['vip4']) {
                return $price / 10 * $set->re_vip4;
            }
            if ($level == UserLevel::$keys['vip5']) {
                return $price / 10 * $set->re_vip5;
            }
            if ($level == UserLevel::$keys['vip6']) {
                return $price / 10 * $set->re_vip6;
            }

        }

        // // 商品区, 10%
        // if (ProductArea::checkGeneral($product_id)) {
        //     return $price * 0.1;
        // }
        //
        // // 福利区
        // if (ProductArea::checkF($product_id)) {
        //     $diff = SetProductCommission::find()
        //         ->where(['product_id' => $product_id])
        //         ->one();
        //     if ($diff) {
        //         if ($diff->f2 > 0 && $level >= UserLevel::$keys['vip1']) {
        //             return $diff->f2;
        //         }
        //         if ($diff->f1 > 0) {
        //             return $diff->f1;
        //         }
        //     }
        // }

        return $price;
    }

    /**
     * Save timestamp
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    /**
     * with brand
     * @return \yii\db\ActiveQuery
     */
    public function getBrand()
    {
        return $this->hasOne(Brand::class, ['id' => 'brand_id']);
    }

    /**
     * with category
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(ProductCategory::class, ['id' => 'category_id']);
    }

    /**
     * with area
     * @return \yii\db\ActiveQuery
     */
    public function getArea()
    {
        return $this->hasMany(ProductAreaList::class, ['product_id' => 'id']);
    }

    /**
     * with property
     * @return \yii\db\ActiveQuery
     */
    public function getProperties()
    {
        return $this->hasMany(ProductProperty::class, ['product_id' => 'id'])
            ->where(['status' => ProductProperty::$statusMapping['OK']]);
    }

    /**
     * with sku
     * @return \yii\db\ActiveQuery
     */
    public function getSku()
    {
        return $this->hasMany(ProductSku::class, ['product_id' => 'id'])
            ->where(['status' => ProductSku::$statusMapping['OK']]);
    }

    /**
     * with sku name
     * @return \yii\db\ActiveQuery
     */
    public function getSkuName()
    {
        return $this->hasMany(ProductSkuName::class, ['product_id' => 'id'])
            ->where(['status' => ProductSkuName::$statusMapping['OK']]);
    }

    /**
     * with images
     * @return \yii\db\ActiveQuery
     */
    public function getImage()
    {
        return $this->hasMany(ProductImage::class, ['product_id' => 'id']);
    }

    /**
     * with main image
     * @return \yii\db\ActiveQuery
     */
    public function getMainImage()
    {
        return $this->hasOne(Images::class, ['id' => 'main_image']);
    }

    /**
     * with score cost
     *
     * @return \yii\db\ActiveQuery
     */
    public function getScoreCost()
    {
        return $this->hasOne(ProductScoreCost::class, ['id' => 'score_cost_id']);
    }

    // 佣金与差价
    public function getCommissionDiff()
    {
        return $this->hasOne(SetProductCommission::class, ['product_id' => 'id']);
    }
}
